<?php

/**
 * Description of UcetAdmin
 *
 * @author David Dusek
 */
class NovinkyAdminPresenter extends AdminPresenter {
     public function renderDefault() {
        $news = new NewsModel($this->db);
        $this->template->allNews = $news->order("inserted_date DESC");
    }
    
    public function renderPridat() {
        
    }
    
    public function renderUpravit($id) {
        
    }
    
    public function handleSmazat($id) {
        $newsModel = new NewsModel($this->db);
        $news = $newsModel->where("id", $id)->delete();
        
        if ($news) {
            $this->flashMessage("Novinka byla smazána");
        } else {
            $this->flashMessage("Novinku se nepodařilo odsranit. Zkuste to prosím znovu.", "error");
        }                
        $this->invalidateControl();
    }
        
    protected function createComponentNewsForm() {
        $form = new NAppForm();
        $form->addText("title", "Titulek:")
                ->setRequired("titulek novinky je povinný")
                ->addRule(NForm::MAX_LENGTH, "délka titulku je maximálně 100 znaků", 100)
                ->getControlPrototype()->class("form-wide");
        $form->addTextArea("content", "Text novinky:")
                ->getControlPrototype()->class("nic-edit");        
        $form->addSubmit('send', 'Uložit');
        
        if ($this->action == "upravit") {
            $id = $this->getParam("id");
            $form->addHidden("id")->setDefaultValue($this->getParam("id"));
            
            $newsModel = new NewsModel($this->db);
            $news = $newsModel->get($id);            
            $form->setDefaults(array(                
                "title" => $news->title,
                "content" => $news->content,
            ));
        }

        $form->onSuccess[] = $this->newsFormSubmitted;
        return $form;
    }
    
    /**
     *
     * @param NAppForm $form 
     */
    public function newsFormSubmitted($form) {
        $values = $form->getValues();
        
        $newsModel = new NewsModel($this->db);
        
        if ($this->action == "pridat") {
            $newsModel->insert(array(
                "title" => $values["title"],                
                "content" => $values["content"],                
            ));
            $this->flashMessage("Novinka byla přidána.");
            $this->redirect("default");
        } else if ($this->action == "upravit") {
            $newsModel->where("id", $values["id"])->update(array(
                "title" => $values["title"],
                "content" => $values["content"],
            ));
            $this->flashMessage("Novinka byla upravena.");
            $this->redirect("this");
        }
    }   
}
